<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Http\Request;
use function PHPUnit\Framework\returnArgument;


class GoodsController extends BaseController
{
    //文章列表
    public function getGoodsLists()
    {
        list($offset,$limit)=$this->page();
        $result=Goods::with(['user'])
            ->orderBy("created_at",'desc')
            ->offset($offset)
            ->limit($limit)
            ->get()->toArray();

        foreach ($result as &$value){
            $diffTime=time()-strtotime($value['created_at']);
            $value['diff_time']=$this->diffTime($diffTime);
        }
        return[
            'code'=>0,
            'total_nums'=>Goods::count(),
            'data'=>$result,
            'msg'=>"成功",
        ];
    }

    //文章详情
    public function goodsDetail(Request $request){
        try {
            $request->validate([
                'id'=>'required|integer'
            ]);
        }catch (\Exception $e){
            exit(json_encode([
                'code'=>-1,
                'data'=>null,
                'msg'=>"page,limit必须是整形",
            ],JSON_UNESCAPED_UNICODE));
        }
        $id=$request->get('id');
        $result=Goods::getGoodsDetailByID($id);
        return[
            'code'=>0,
            'data'=>$result,
            'msg'=>"成功",
        ];
    }
    function diffTime($diffTime)
    {
        if ($diffTime < 60){
            return $diffTime.'秒前';
        }elseif ($diffTime > 60 && $diffTime < 60 * 60){
            return ceil(($diffTime/60)).'分钟前';
        }elseif ($diffTime > 60 * 60 && $diffTime < 60 * 60 * 24){
            return ceil(($diffTime/60/24)).'小时前';
        }else{
            return  'emmmm';
        }
    }



}
